const product_cate_model = require('../../models/project/category');
const BaseComponent = require('../../prototype/baseComponent');
class ProjectCate extends BaseComponent {
  constructor() {
    super()
  }
  //获取列表
  getList = async (req, res, next) => {
    try {
      let { page = 1, limit = 10 } = req.query
      let list = await product_cate_model.find({}, { '__v': 0 }, { lean: true }).skip(Number((page - 1) * limit)).limit(Number(limit))
      let total = await product_cate_model.estimatedDocumentCount()
      list.forEach((item) => {
        item.create_time = this.formatTime(item.create_time)
        item.update_time = this.formatTime(item.update_time)
      })
      let data = {
        list: list,
        total: total
      }
      this.sendSuccess(res, data, '查询成功')
    } catch (err) {
      this.sendError(res, err)
    }
  }
  //新增项目
  add = async (req, res, next) => {
    try {
      let { name = '', describe = '', href = '', img_url = '1', status = true, sort = 0 } = req.body
      // if (!start_time || !end_time) throw new Error("请填写开始时间或结束时间")
      let new_project = {
        _id: this.createId(),
        name: name,
        img_url: img_url,
        describe: describe,
        status: status,
        href: href,
        sort: sort
      }
      await product_cate_model.create(new_project)
      this.sendSuccess(res, '', '新增成功')
    } catch (err) {
      this.sendError(res, err)
    }
  }
  //更新项目
  update = async (req, res, next) => {
    try {
      let { _id, name = '', describe = '', href = '', img_url = '1', status = true, sort = 0 } = req.body
      if (!_id) throw new Error("请填写项目id")
      let obj = {
        _id: _id,
        name: name,
        img_url: img_url,
        describe: describe,
        status: status,
        href: href,
        sort: sort
      }
      let details = await product_cate_model.findOneAndUpdate({ _id: _id }, { $set: obj })
      if (!details) throw new Error("没有此项目，请检查项目id是否正确")
      this.sendSuccess(res, '', '修改成功')
    } catch (err) {
      this.sendError(res, err)
    }
  }
  //删除项目
  del = async (req, res, next) => {
    try {
      let { _id = '' } = req.body
      if (!_id) throw new Error("请填写项目id")
      let details = await product_cate_model.findOneAndRemove({ _id: _id })
      if (!details) throw new Error("没有此项目，请检查项目id是否正确")
      this.sendSuccess(res, '', '删除成功')
    } catch (err) {
      this.sendError(res, err)
    }
  }
}
module.exports = new ProjectCate()